package cn.cs.mathgo.sso.server;

import cn.cs.mathgo.common.util.Md5PasswordEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;


/**
 *  spring security 认证配置中新
 */
@Configuration
public class SsoSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyAuthenticationProvider provider;
    @Autowired
    private  AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception{
    }
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/authentication/require")
                .loginProcessingUrl("/authentication/form")
                .successHandler(authenticationSuccessHandler)
                .and().authorizeRequests()
                .antMatchers("/authentication/require",
                        "/authentication/form",
                        "/**/*.js",
                        "/**/*.css",
                        "/**/*.jpg",
                        "/**/*.png",
                        "/**/*.woff2",
                        "org/user/login"
                )
                .permitAll()
                .anyRequest()
                //.authenticated()
                .access("@resourceService.hasPermission(request,authentication)")
                .and()
                .logout().logoutSuccessUrl("/user")
                .and()
                .csrf().disable();
//        http.formLogin().and().authorizeRequests().anyRequest().authenticated();
    }

    /**
     * 使用我们自定义的密码验证
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       // auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
        //将验证过程交给自定义验证工具
        auth.authenticationProvider(provider);
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
       // return new BCryptPasswordEncoder();
        return new MPasswordEncoder();
    }
    /**
     * 自定义加密方法
     */
    public   class  MPasswordEncoder implements PasswordEncoder{
        @Override
        public String encode(CharSequence charSequence) {
            String msg = charSequence.toString();
            String [] arr=msg.split(",");
            String encryptPasswd =new Md5PasswordEncoder().encodePassword(arr[0], arr[1]);
            return encryptPasswd;
        }
        @Override
        public boolean matches(CharSequence rawPassword, String encodedPassword) {
            if (encodedPassword != null && encodedPassword.length() != 0) {

                return BCrypt.checkpw(rawPassword.toString(), encodedPassword);

            } else {
                logger.warn("Empty encoded password");
                return false;
            }
        }
    }
}
